package com.example.screenshotpc;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.StrictMode;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.common.FtpOption;
import com.arialyy.aria.core.task.DownloadTask;
import com.arialyy.aria.util.ALog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import gdut.bsx.share2.Share2;
import gdut.bsx.share2.ShareContentType;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageButton btn;

    private static String URIx = null;
    private Button btn_connect;
    private ImageButton btn_shotwindow;
    private ImageButton btn_history;
    private ImageButton btn_gif;
    private Button btn_debug;
    private DatagramSocket socket = null;
    private InetAddress serverAddress = null;
    private ProgressDialog progressDialog;

    public static final int DELAY = 1000;
    private static long lastClickTime = 0;
    int ax=1;
    private static int jiance=0;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};
    private final String PREFS_NAME = "user";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Aria.download(this).register();
        verifyStoragePermissions(this);
        setContentView(R.layout.activity_main);
        btn = (ImageButton) findViewById(R.id.imageButton);
        btn_connect = (Button) findViewById(R.id.storebt);
        btn_shotwindow = (ImageButton) findViewById(R.id.imageButton2);
        btn_gif=(ImageButton)findViewById(R.id.gifbut);
        btn_history=(ImageButton)findViewById(R.id.history);
        btn_debug=(Button)findViewById(R.id.debug);
        btn_debug.setOnClickListener(this);
        btn.setOnClickListener(this);
        btn_connect.setOnClickListener(this);
        btn_shotwindow.setOnClickListener(this);
        btn_gif.setOnClickListener(this);
        btn_history.setOnClickListener(this);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.mymenu,menu);
        return true;
    }
    //关于界面
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.menu_login:
                Toast.makeText(this,"开源软件,感谢使用 v4.0", Toast.LENGTH_SHORT).show();
                break;
            case R.id.menu_file:
                String path = "%2fPictures%2fPC%2f";
                Uri uri = Uri.parse("content://com.android.externalstorage.documents/document/primary:" + path);
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("*/*");//想要展示的文件类型
                intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, uri);
                startActivityForResult(intent, 1);
                break;
            case R.id.menu_pc:
                Uri urix = Uri.parse("https://gitee.com/dwaedwe12/ScreenshotPC2/releases");
                Intent intentx = new Intent(Intent.ACTION_VIEW, urix);
                startActivity(intentx);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            share(uri);

        }
    }


    public void share(Uri uri) {

        //三方库分享调用
        new Share2.Builder(this)
                // 指定分享的文件类型
                .setContentType(ShareContentType.IMAGE)
                // 设置要分享的文件 Uri
                .setShareFileUri(uri)
                // 设置分享选择器的标题
                .setTitle("Share")
                .build()
                // 发起分享
                .shareBySystem();


    }
    //按钮事件
    @RequiresApi(api = Build.VERSION_CODES.R)
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imageButton://全屏按钮
                if (check() == 1)
                    break;
                long currentTime = System.currentTimeMillis();
                if (currentTime-lastClickTime>DELAY){
                    lastClickTime = currentTime;
                }else{
                    return;
                }
                shenqingtupian();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        savephotobyaria();
                    }
                }, 1000);
                break;

            case R.id.storebt://保存按钮
                historyipstore();
                break;


            case R.id.imageButton2://局部按钮
                currentTime = System.currentTimeMillis();
                if (currentTime-lastClickTime>1500){
                    lastClickTime = currentTime;
                }else{
                    return;
                }
                if (check() == 1)
                    break;
                shenqingtupian2();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        savephotobyaria();
                    }
                }, 1300);
                break;
            case R.id.history:
                gethisrotyip();
                break;
            case R.id.gifbut:
                currentTime = System.currentTimeMillis();
                if (currentTime-lastClickTime>1000){
                    lastClickTime = currentTime;
                }else{
                    return;
                }
                progressDialog = ProgressDialog.show(this, "", "搜索中");
                TimerTask task = new TimerTask() {
                    @Override
                    public void run() {
                        /**
                         *要执行的操作
                         */
                        progressDialog.dismiss();
                    }
                };
                Timer timer = new Timer();
                timer.schedule(task, 990);//3秒后执行TimeTask的run方法
                EditText text1x = (EditText) findViewById(R.id.PCIP);
                udpjieshou(text1x);
                break;
            case R.id.debug:
                Intent intent = new Intent();
                //setClass函数的第一个参数是一个Context对象
                //Context是一个类，Activity是Context类的子类，也就是说，所有的Activity对象，都可以向上转型为Context对象
                //setClass函数的第二个参数是一个Class对象，在当前场景下，应该传入需要被启动的Activity类的class对象
                intent.setClass(MainActivity.this, MainActivity2.class);
                startActivity(intent);
                break;
            default:
                break;

        }
    }
    //自动搜索电脑
    public void udpjieshou(EditText text) {

        new Thread() {
            public void run() {
                while (true) {
                    try {
                        String a = new String("abc");
                        DatagramSocket dgSocket = null;
                        int port = 9832;
                        dgSocket = new DatagramSocket(null);
                        dgSocket.setReuseAddress(true);
                        dgSocket.bind(new InetSocketAddress(port));
                        byte[] by = new byte[1024];
                        DatagramPacket packet = new DatagramPacket(by, by.length);
                        dgSocket.receive(packet);
                        String str = new String(packet.getData(), 0, packet.getLength());
                        text.post(new Runnable() {
                            public void run() {
                                text.setText(str, TextView.BufferType.NORMAL);
                            }
                        });
                        Looper.prepare();
                            Toast.makeText(MainActivity.this, "搜索到"+str, Toast.LENGTH_SHORT).show();
                            Looper.loop();


                    } catch (IOException e) {

                        e.printStackTrace();
                    }
                }
            }
        }.start();

    }

    //链接测试
    public void connects() {

        EditText text1 = (EditText) findViewById(R.id.PCIP);
        String ip = text1.getText().toString();//murl为文本框内容
        try {
            socket = new DatagramSocket(12345);
            serverAddress = InetAddress.getByName(ip);  //②
        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();
        }
        Toast.makeText(MainActivity.this, "尝试链接", Toast.LENGTH_LONG).show();
        progressDialog = ProgressDialog.show(this, "", "尝试连接中");
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                /**
                 *要执行的操作
                 */
                progressDialog.dismiss();
            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 3000);//3秒后执行TimeTask的run方法
        try {
            String sendData = "plstes";
            byte data[] = sendData.getBytes();
            //这里的8888是接收方的端口号
            DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress, 21211);   //③
            socket.send(packet);
        } catch (Exception e) {
            e.printStackTrace();
        }
        checkudp();
        text1=null;
        ip=null;

    }

    //申请图片
    public void shenqingtupian() {

        EditText text1 = (EditText) findViewById(R.id.PCIP);

        String ip = text1.getText().toString();//murl为文本框内容

        try {
            socket = new DatagramSocket(12345);
            serverAddress = InetAddress.getByName(ip);  //②

        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();

        }
        Toast.makeText(MainActivity.this, "申请让电脑截图中", Toast.LENGTH_SHORT).show();

        progressDialog = ProgressDialog.show(this, "", "下载中");
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                /**
                 *要执行的操作
                 */
                progressDialog.dismiss();
            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 990);//3秒后执行TimeTask的run方法

        try {
            String sendData = "shot";
            byte data[] = sendData.getBytes();
            //这里的8888是接收方的端口号
            DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress, 21211);   //③
            socket.send(packet);
        } catch (Exception e) {
            e.printStackTrace();

        }
        text1=null;

    }

    //申请局部截图
    public void shenqingtupian2() {

        EditText text1 = (EditText) findViewById(R.id.PCIP);

        String ip = text1.getText().toString();//murl为文本框内容

        try {
            socket = new DatagramSocket(12345);
            serverAddress = InetAddress.getByName(ip);  //②

        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();

        }
        Toast.makeText(MainActivity.this, "申请局部截图中", Toast.LENGTH_SHORT).show();
        progressDialog = ProgressDialog.show(this, "", "下载中");
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                /**
                 *要执行的操作
                 */
                progressDialog.dismiss();
            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 1490);//3秒后执行TimeTask的run方法

        try {
            String sendData = "shotwindows";
            byte data[] = sendData.getBytes();
            //这里的8888是接收方的端口号
            DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress, 21211);   //③
            socket.send(packet);
        } catch (Exception e) {
            e.printStackTrace();

        }
        text1=null;
    }




    //ip检测
    public int check() {
        EditText text1 = (EditText) findViewById(R.id.PCIP);
        String string = text1.getText().toString();//murl为文本框内容
        /*正则表达式*/
        String ip = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
                + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";//限定输入格式
        Pattern p = Pattern.compile(ip);
        Matcher m = p.matcher(string);
        boolean b = m.matches();
        if (b == false) {
            Toast.makeText(this, "IP格式输入错误", Toast.LENGTH_LONG).show();
            return 1;
        }
        return 0;
    }

    //UDP接收
    public void checkudp() {

        new Thread() {
            public void run() {
                while (true) {
                    try {
                        String a = new String("abc");
                        DatagramSocket dgSocket = null;
                        int port = 21222;
                        dgSocket = new DatagramSocket(null);
                        dgSocket.setReuseAddress(true);
                        dgSocket.bind(new InetSocketAddress(port));
                        byte[] by = new byte[1024];
                        DatagramPacket packet = new DatagramPacket(by, by.length);
                        dgSocket.receive(packet);
                        String str = new String(packet.getData(), 0, packet.getLength());
                        if (a.equals(str)) {
                            //jiance=1;
                            Looper.prepare();
                            Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
                     }.start();
            }

    //权限申请
    public static void verifyStoragePermissions(Activity activity) {

        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //历史IP与密码
    public void historyipstore(){
        EditText text1 = (EditText) findViewById(R.id.PCIP);
        String ipnn = text1.getText().toString();//murl为文本框内容
        EditText text2 = (EditText) findViewById(R.id.password);
        String passwordnn = text2.getText().toString();//murl为文本框内容

        SharedPreferences userInfo = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = userInfo.edit();//获取Editor

        //得到Editor后，写入需要保存的数据
        editor.putString("userip", ipnn);
        editor.putString("userpassword",passwordnn);
        editor.commit();//提交修改
        Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
    }
    private void gethisrotyip(){
        SharedPreferences userInfo = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        String ipmm = userInfo.getString("userip", null);//读取username
        String password=userInfo.getString("userpassword", null);
        EditText text1 = (EditText) findViewById(R.id.PCIP);
        text1.setText(ipmm, TextView.BufferType.NORMAL);

        EditText text2 = (EditText) findViewById(R.id.password);
        text2.setText(password, TextView.BufferType.NORMAL);

    }

    //用aira下载ftp到缓存中
    public void savephotobyaria() {
        EditText textBOX = (EditText) findViewById(R.id.password);
        String password = textBOX.getText().toString();//murl为文本框
        EditText textBOXip = (EditText) findViewById(R.id.PCIP);
        String ipad = textBOXip.getText().toString();//murl为文本框
        //以上为获取两个文本框
        FtpOption ftpOption = new FtpOption();
        ftpOption.login("admin", password);
        String murl = "ftp://" + ipad + ":23235/tempcap.png";//debug阶段，以后可以加上混乱端口
        Long mImageTime = System.currentTimeMillis();
        String imageDate = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date(mImageTime));
        String SCREENSHOT_FILE_NAME_TEMPLATE = "Screenshot_%s.png";//图片名称，以"Screenshot"+时间戳命名
        String mImageFileName = String.format(SCREENSHOT_FILE_NAME_TEMPLATE, imageDate);
        String Path = getExternalFilesDir(Environment.DIRECTORY_PICTURES) + mImageFileName;

        long taskId = Aria.download(this)
                .loadFtp(murl) // 下载地址
                .option(ftpOption)
                .setFilePath(Path) // 设置文件保存路径
                .create();

        URIx = Path;//把局部路径转换为全局路径，即下载完到缓存文件夹的图片
    }

    //安卓10缓存路径转mediastore真正进图库
    public static void putBitmapToMedia(Context context, String URI) {
        String fileName;
        Long mImageTime = System.currentTimeMillis();
        String imageDate = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date(mImageTime));
        String SCREENSHOT_FILE_NAME_TEMPLATE = "t_%s.png";//图片名称，以"Screenshot"+时间戳命名
        String mImageFileName = String.format(SCREENSHOT_FILE_NAME_TEMPLATE, imageDate);
        fileName = mImageFileName;
        Bitmap mbitmap;
        mbitmap = BitmapFactory.decodeFile(URI);
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
        values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES
                + File.separator + "PC");
        Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        try {
            OutputStream out = context.getContentResolver().openOutputStream(uri);
            mbitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
            File file = new File(URIx);
            file.delete();

        } catch (IOException e) {

            e.printStackTrace();
        }
    }

    //安卓9及以下拷贝缓存到文件夹
    public void putcachetomeida(String URI)throws IOException{
        Bitmap mbitmap;
        mbitmap = BitmapFactory.decodeFile(URI);
        String dir = Environment.getExternalStorageDirectory() + File.separator + "Pictures"
                + File.separator + "PC" + File.separator;
        String fileName = System.currentTimeMillis() + ".png";
        String subForder = dir;
        File foder = new File(subForder);
        if (!foder.exists()) {
            foder.mkdirs();
        }
        File myCaptureFile = new File(subForder, fileName);
        if (!myCaptureFile.exists()) {
            myCaptureFile.createNewFile();
        }
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        mbitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
        bos.flush();
        bos.close();
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(foder);
        intent.setData(uri);
        this.sendBroadcast(intent);//这个广播的目的就是更新图库，发了这个广播进入相册就可以找到你保存的图片了！，记得要传你更新的file哦
    }


    //下载成功后才开始拷贝缓存和一些任务
    @Download.onTaskComplete
    void taskComplete(DownloadTask task) {
        Toast.makeText(this, "下载完成", Toast.LENGTH_SHORT).show();
        ImageView imageView = (ImageView) findViewById(R.id.imageView);
        Glide.with(this)
                .load(URIx)
                .diskCacheStrategy(DiskCacheStrategy.NONE)//禁用磁盘缓存
                .skipMemoryCache(true)//跳过内存缓存
                .into(imageView);
        //不同版本拷贝语句
        if (Build.VERSION.SDK_INT > 29) {
            putBitmapToMedia(this, URIx);//下载完成后BITMAP拷贝
        }else{
            try {
                putcachetomeida(URIx);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    //下载失败toast
    @Download.onTaskFail void taskFail(DownloadTask task, Exception e) {
        Toast.makeText(this,"下载失败，可能是密码错误或未连接上",Toast.LENGTH_SHORT).show();
        System.out.println("错误信息");
        System.out.println(ALog.getExceptionString(e));
    }


}

